package user

import (
	"context"
	"errors"
	"gitee.com/CrazyMage/lite-note/internal/controller/http/v1/request"
	"gitee.com/CrazyMage/lite-note/internal/controller/http/v1/response"
	"gitee.com/CrazyMage/lite-note/internal/entity"
	"gitee.com/CrazyMage/lite-note/internal/repo"
	"gitee.com/CrazyMage/lite-note/pkg/utils"
	"gorm.io/gorm"
	"log"
)

type UseCase struct {
	repo repo.UserRepo
}

func New(r repo.UserRepo) *UseCase {
	return &UseCase{repo: r}
}

func (uc *UseCase) Register(ctx context.Context, req *request.ServiceRegisterReq) error {

	//1.查询数据库是否已经注册过了
	user, err := uc.repo.FindUserByUserName(req.UserName)

	//2.err == nil ,说明用户已经存在
	if err == nil {
		return errors.New("用户已存在")
	}

	//3. err !=nil的情况下，如果是记录没有找到，则注册
	if errors.Is(err, gorm.ErrRecordNotFound) {
		//3.1没有则注册
		user = &entity.User{
			UserName: req.UserName,
		}

		if err = user.SetPassword(req.Password); err != nil {
			return err
		}

		if err = uc.repo.CreateUser(user); err != nil {
			return err
		}

		return nil
	}

	//4.返回其他错误
	return err

}

func (uc *UseCase) Login(ctx context.Context, req *request.ServiceLoginReq) (resp response.ServiceLoginResp, err error) {

	//1.根据用户名查询用户
	user, err := uc.repo.FindUserByUserName(req.UserName)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			err = errors.New("user is not exist")
		}
		return
	}

	//2.检查用户密码
	if !user.CheckPassword(req.Password) {
		err = errors.New("账号或者密码错误")
		log.Println(err)
		return
	}

	//3.生成token
	token, err := utils.GenerateToken(user.ID, req.UserName)
	if err != nil {
		log.Println(err)
		return
	}

	//4.生成结果
	resp = response.ServiceLoginResp{
		ID:       user.ID,
		UserName: user.UserName,
		CreateAt: user.Model.CreatedAt.Unix(),
		Token:    token,
	}

	return resp, nil
}
